package com.admin_system.service.impl;

import com.admin_system.entity.NoticeRead;
import com.admin_system.service.NoticeReadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 公告已读记录服务实现类
 */
@Service
@Slf4j
public class NoticeReadServiceImpl implements NoticeReadService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public boolean markNoticeAsRead(Long noticeId, Long userId, String userName) {
        try {
            // 先检查是否已经存在记录
            String checkSql = "SELECT COUNT(*) FROM notice_reads WHERE notice_id = ? AND user_id = ?";
            Integer count = jdbcTemplate.queryForObject(checkSql, Integer.class, noticeId, userId);

            if (count != null && count > 0) {
                log.info("用户[{}]已经阅读过公告[{}]，不再重复记录", userId, noticeId);
                return true; // 已经阅读过，视为成功
            }

            // 插入新记录
            String sql = "INSERT INTO notice_reads (notice_id, user_id, user_name, read_time) VALUES (?, ?, ?, ?)";
            int rows = jdbcTemplate.update(sql, noticeId, userId, userName, LocalDateTime.now());
            
            return rows > 0;
        } catch (Exception e) {
            log.error("标记公告已读失败", e);
            return false;
        }
    }

    @Override
    public List<NoticeRead> getNoticeReadRecords(Long noticeId) {
        try {
            String sql = "SELECT * FROM notice_reads WHERE notice_id = ? ORDER BY read_time DESC";
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(NoticeRead.class), noticeId);
        } catch (Exception e) {
            log.error("获取公告已读记录失败", e);
            return List.of(); // 返回空列表
        }
    }

    @Override
    public boolean hasUserReadNotice(Long noticeId, Long userId) {
        try {
            String sql = "SELECT COUNT(*) FROM notice_reads WHERE notice_id = ? AND user_id = ?";
            Integer count = jdbcTemplate.queryForObject(sql, Integer.class, noticeId, userId);
            return count != null && count > 0;
        } catch (Exception e) {
            log.error("检查用户是否已读公告失败", e);
            return false;
        }
    }

    @Override
    public int getUnreadNoticeCount(Long userId) {
        try {
            String sql = "SELECT COUNT(*) FROM notices n WHERE NOT EXISTS " +
                    "(SELECT 1 FROM notice_reads nr WHERE nr.notice_id = n.id AND nr.user_id = ?)";
            Integer count = jdbcTemplate.queryForObject(sql, Integer.class, userId);
            return count != null ? count : 0;
        } catch (Exception e) {
            log.error("获取未读公告数量失败", e);
            return 0;
        }
    }

    @Override
    public List<Map<String, Object>> getNoticeUnreadUsers(Long noticeId) {
        try {
            log.info("开始查询公告[{}]的未读用户列表", noticeId);
            
            // 查询所有用户，并排除已经阅读过该公告的用户
            String sql = "SELECT u.id as userId, u.username, COALESCE(u.full_name, u.username) as userName " +
                    "FROM users u " +
                    "WHERE NOT EXISTS (SELECT 1 FROM notice_reads nr WHERE nr.notice_id = ? AND nr.user_id = u.id) " +
                    "ORDER BY u.username";
            
            log.info("执行SQL查询: {}", sql.replace("?", noticeId.toString()));
            
            List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, noticeId);
            
            log.info("查询结果: {} 条记录", results.size());
            if (!results.isEmpty()) {
                Map<String, Object> firstUser = results.get(0);
                log.info("第一条记录: {}", firstUser);
                log.info("记录字段: {}", firstUser.keySet());
            }
            
            return results;
        } catch (Exception e) {
            log.error("获取公告[{}]未读用户列表失败", noticeId, e);
            return List.of(); // 返回空列表
        }
    }
} 